package com.bert.generator.base;

import cn.hutool.core.util.StrUtil;
import com.bert.generator.base.abs.AbstractGenerateCode;
import com.bert.generator.base.db.DBInfo;
import com.bert.generator.base.db.TableInfo;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 生成java项目代码
 */
public class GenerateJavaCode extends AbstractGenerateCode {

    private Map<String, Object> dataMap = new HashMap<>();
    private String moduleName;
    private String packageName;
    private String tableName;
    private List<String> moduleList;
    private Map<String, List<JavaPathConfig>> pathConfigMap;

    public GenerateJavaCode(GeneratorConfig generatorConfig) {
        super(generatorConfig);
    }

    @Override
    protected void doGenerator() {
        // 初始化数据
        dataMap.put("projectName", generatorConfig.getProjectName());
        dataMap.put("version", generatorConfig.getVersion());
        dataMap.put("author", generatorConfig.getAuthor());
        moduleList = !CollectionUtils.isEmpty(generatorConfig.getOnlyNeedModules()) ? generatorConfig.getOnlyNeedModules() : pathConfig.getmoduleList();
        pathConfigMap = pathConfig.getPathConfigList();
        // 获取每一个模块对应的表信息
        Map<String, List<TableInfo>> moduleTables = new HashMap<>();
        for (DBInfo dbInfo : dbInfos) {
            for (TableInfo tableInfo : dbInfo.getTableInfos()) {
                List<TableInfo> list = moduleTables.getOrDefault(tableInfo.getModuleName(), new ArrayList<>());
                list.add(tableInfo);
                moduleTables.put(tableInfo.getModuleName(), list);
            }
        }
        initModules(moduleTables);
    }

    /**
     * 初始化每个模块maven工程
     *
     * @param moduleTables 数据
     */
    private void initModules(Map<String, List<TableInfo>> moduleTables) {
        Set<String> modules = moduleTables.keySet();
        for (String module : modules) {
            moduleName = module;
            dataMap.put("moduleName", moduleName);
            // 生成pom文件
            createPomFile();
            // 获取模块下的所以表信息
            List<TableInfo> tableInfos = moduleTables.get(module);
            tableInfos.forEach(tableInfo -> {
                // 初始化数据
                initTableData(tableInfo);
                // 生成配置模块的代码
                initModuleAll();
            });
        }
    }

    /**
     * 生成${projectName}-${moduleName}-all中的代码以及文件夹
     */
    private void initModuleAll() {
        moduleList.forEach(m -> {
            List<JavaPathConfig> pathConfigList = pathConfigMap.get(m);
            if (Objects.isNull(pathConfigList)) {
                return;
            }
            pathConfigList.forEach(p -> {
                String root = joinRoot(p.getModule()) + "/src/main/java/com/hkbt/" + moduleName + "/" + p.getModule() + "/" + packageName;
                String filePath = root + "/" + p.getChildrenModule() + "/" + tableName + p.getFileExtension();
                templateProcess(filePath, p.getTemplatePath(), dataMap);
            });
        });

    }

    /**
     * 初始化模板中的数据
     *
     * @param tableInfo
     */
    private void initTableData(TableInfo tableInfo) {
        packageName = tableInfo.getPackageName();
        tableName = tableInfo.baseClassName();
        String notes = tableInfo.getComment();
        if (tableInfo.getComment().split("-").length > 1) {
            notes = tableInfo.getComment().split("-")[1];
        }
        dataMap.put("notes", notes);
        dataMap.put("table_name", tableInfo.getTableName());
        dataMap.put("packageName", packageName);
        dataMap.put("tableName", tableName);
        dataMap.put("lowerTableName", StrUtil.lowerFirst(tableInfo.baseClassName()));
        dataMap.put("comment", tableInfo.getComment());
        dataMap.put("columnAllList", tableInfo.getColumnInfoList());
        // 该表中的过滤后的列信息
        dataMap.put("columnInfoList", tableInfo.getColumnInfoList().stream().filter(f -> !generatorConfig.getColumnFilter().contains(f.getFieldName())).collect(Collectors.toList()));
    }

    /**
     * 生成各个模块的pom文件
     */
    private void createPomFile() {
        String root = generatorConfig.getGeneraPath() + "/" + generatorConfig.getProjectName() + "-" + moduleName + "/";
        templateProcess(root + "/pom.xml", "templates/Java/Pom.ftl", dataMap);
        moduleList.forEach(m -> {
            String path = root + generatorConfig.getProjectName() + "-" + moduleName + "-" + m;
            templateProcess(path + "/pom.xml", "templates/Java/" + m + "/Pom.ftl", dataMap);
            //生成创建src下面各个空文件夹
            createDictionary(path + "/src/main/resources/");
            createDictionary(path + "/src/test/java/");
        });
    }

    /**
     * 拼接出
     * ${projectName}-${moduleName}/${projectName}-${moduleName}-suffix
     *
     * @param suffix 参数
     * @return 拼接的路径
     */
    private String joinRoot(String suffix) {
        return generatorConfig.getGeneraPath() + "/" + generatorConfig.getProjectName() + "-" + moduleName + "/" + generatorConfig.getProjectName() + "-" + moduleName + "-" + suffix;
    }


}
